package org.robot.scm.platform.server.handler.archery;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.net.HttpCookie;
import java.util.List;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.server.handler.BaseHandler;
import org.robot.scm.pojos.archery.ArcheryStatusEnum;
import org.robot.scm.pojos.archery.ListResponse;
import org.robot.scm.pojos.archery.WorkflowRows;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.JsonHelper;

@Slf4j
@NoArgsConstructor
public class ArcheryListHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/archery/list";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        sendSuccessResponse(exchange, "查询成功", JsonHelper.toJSONString(getList()));
    }

    private static List<WorkflowRows> getList() {
        String token = RedisCacheHelper.get("archery_token");
        String sessionId = RedisCacheHelper.get("archery_session");

        String start = DateTool.format(DateTool.current(-2), DateTool.PATTERN_5);
        String end = DateTool.format(DateTool.current(), DateTool.PATTERN_5);
        String body = String.format("limit=100&offset=0&navStatus=&instance_id=&group_id=&start_date=%s&end_date=%s&search=", start, end);
        String listUrl = ArcheryConfig.ARCHERY_URL + "/sqlworkflow_list/";
        HttpResponse response = HttpUtil.createRequest(Method.POST, listUrl)
                .body(body)
                .header("X-CSRFToken", token)
                .cookie(new HttpCookie("csrftoken", token), new HttpCookie("sessionid", sessionId))
                .execute();

        String result = response.body();
        if (StringUtils.contains(result, "CSRF验证失败") || StringUtils.isBlank(result)) {
            ArcheryHelper.loginAndSession();
            return getList();
        }
        ListResponse workflows = JsonHelper.toObject(response.body(), ListResponse.class);
        for (WorkflowRows rows : workflows.getRows()) {
            rows.setStatusDesc(ArcheryStatusEnum.getDescByVal(rows.getStatus()));
        }
        // 对results按照id倒序
        workflows.getRows().sort((o1, o2) -> o2.getId() - o1.getId());
        return workflows.getRows();
    }
}
